using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using Geekees.App.Cashbook.Lib;
using Geekees.App.Cashbook.Lib.BLL;
using Geekees.App.Cashbook.Lib.Entity;
using Geekees.App.Cashbook.Lib.Helper;

namespace Geekees.App.Cashbook.Web
{
	/// <summary>
	/// Summary description for ChangePassword.
	/// </summary>
	public class ChangePassword : PageBase
	{
		protected System.Web.UI.WebControls.TextBox txtOldPwd;
		protected System.Web.UI.WebControls.TextBox txtNewPwd;
		protected System.Web.UI.WebControls.TextBox txtConfirmPwd;
		protected System.Web.UI.WebControls.Button btnChange;
	
		private void Page_Load(object sender, System.EventArgs e)
		{
			
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.btnChange.Click += new System.EventHandler(this.btnChange_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void btnChange_Click(object sender, System.EventArgs e)
		{
			string login = LoginManager.GetCurrentUser().Login;
			string oldPwd = MD5Helper.GetMd5Sum( this.txtOldPwd.Text );
			string newPwd = MD5Helper.GetMd5Sum( this.txtNewPwd.Text );
			string conPwd = MD5Helper.GetMd5Sum( this.txtConfirmPwd.Text );

			if( newPwd != conPwd )
			{	
				FlashMessage.SetFlash( "Passwords do not match!", FlashMessage.FlashMessageType.Error );
				return;
			}

			if( !BLSecurity.CheckLogin( login, oldPwd ) )
			{	
				FlashMessage.SetFlash( "The password you gave is incorrect!", FlashMessage.FlashMessageType.Error );
				return;
			}

			if( BLSecurity.ChangePassword( login, oldPwd, newPwd ) )
			{
				BLSecurity.UpdateLastChangePasswordTime( login, DateTime.Now );
				BLSecurity.UpdateTicket( login, MD5Helper.GetMd5Sum( DateTime.Now.ToString() ) );

				LoginManager.Login( login, newPwd );
				FlashMessage.SetFlash( "You password has been changed successfully!");
			}
			else
				FlashMessage.SetFlash( "Error occured when changing password. Please try again later.", FlashMessage.FlashMessageType.Error );
		}
	}
}
